package com.bluexmicro.ota2.ui.screen.index

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.bluexmicro.ota2.MainRoute
import com.livsdesign.picker.file.PickFile

const val url_sdk_odk_android = "https://gitee.com/bluexmicro/ota-library"
const val url_sdk_odk_ios = "https://gitee.com/bluexmicro/otafor-ios"
const val url_download_android_ota_app = "https://www.pgyer.com/63O91X"
//const val url_version_android_ota_app = "https://www.pgyer.com/6b8932623cd5427d66eb747dbf0d19ec"

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun IndexScreen(navHostController: NavHostController) {

    val context = LocalContext.current
    val viewModel: IndexViewModel = viewModel()
    val local = viewModel.local.collectAsState()
    val remote = viewModel.remote.collectAsState()

    LaunchedEffect(Unit) {
        viewModel.checkVersion(context)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(text = "BX OTA") },
                colors = TopAppBarDefaults.smallTopAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                    titleContentColor = MaterialTheme.colorScheme.onPrimary,
                    actionIconContentColor = MaterialTheme.colorScheme.onPrimary.copy(0.8f)
                )
            )
        }
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(it),
            contentPadding = PaddingValues(16.dp)
        ) {

            item {
                Card(
                    shape = RoundedCornerShape(24.dp),
                ) {

                    for ((index, otaType) in OtaType.values().withIndex()) {
                        MenuItem(otaType.title, otaType.desc) {
                            when (otaType) {
                                OtaType.FIRMWARE ->
                                    navHostController.navigate(MainRoute.DFU.path)

                                OtaType.BATCH_FIRMWARE ->
                                    navHostController.navigate(MainRoute.Batch.path)

                                OtaType.FACE ->
                                    navHostController.navigate(MainRoute.Face.path)

                                OtaType.FACE_CUSTOM ->
                                    navHostController.navigate(MainRoute.FaceCustom.path)

                                OtaType.VP9012_BATCH ->
                                    navHostController.navigate(MainRoute.YiKaBatch.path)

                                OtaType.VP9012_CHECK ->
                                    navHostController.navigate(MainRoute.YiKaCheck.path)

                                OtaType.POWER_CONFIG ->
                                    navHostController.navigate(MainRoute.YanConfig.path)
//                                OtaType.DICT ->
//                                    navHostController.navigate(MainRoute.Dict.path)
                            }
                        }
                        if (index < OtaType.values().lastIndex) {
                            Divider(thickness = Dp.Hairline)
                        }
                    }
                }
            }

            item {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 32.dp, start = 16.dp, end = 8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(text = "下载使用 BX-OTA SDK", modifier = Modifier.weight(1f))
                    IconButton(onClick = {
                        val intent = Intent().apply {
                            action = Intent.ACTION_SEND
                            putExtra(
                                Intent.EXTRA_TEXT,
                                "Android BX-OTA SDK:\n$url_sdk_odk_android; \n IOS BX-OTA SDK:\n$url_sdk_odk_ios;"
                            )
                            type = "text/plain"
                        }
                        context.startActivity(intent)
                    }) {
                        Icon(imageVector = Icons.Default.Share, contentDescription = "share")
                    }
                }

                Card(
                    shape = RoundedCornerShape(24.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.LightGray.copy(0.2f)
                    ),
                ) {
                    UrlItem(context, title = "Android", url = url_sdk_odk_android)
                    Divider(thickness = Dp.Hairline)
                    UrlItem(context, title = "IOS", url = url_sdk_odk_ios)
                }

            }



            item {

                Text(
                    text = "版本",
                    modifier = Modifier.padding(top = 32.dp, bottom = 8.dp, start = 16.dp)
                )

                Card(
                    shape = RoundedCornerShape(24.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = Color.LightGray.copy(0.2f)
                    ),
                ) {
                    val n = if (isDebug(context)) "Debug" else "Release"
                    UrlItem(
                        context,
                        title = "当前版本(${local.value.name})",
                        url = n,
                        enable = false
                    )
                    if (remote.value != null) {
                        Divider(thickness = Dp.Hairline)
                        UrlItem(
                            context,
                            title = "发现新版本(${remote.value!!.name})，点击下载",
                            url = url_download_android_ota_app
                        )
                    }
                }
            }
        }
    }

}

private fun isDebug(context: Context): Boolean {
    return context.applicationInfo != null && (context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0)
}

enum class OtaType(val title: String, val desc: String) {
    FIRMWARE("固件升级", "选择后缀为Zip升级包"),
    BATCH_FIRMWARE("批量固件升级", "选择后缀为Zip升级包"),
    FACE("表盘下载", "下载指定的表盘到设备上"),
    FACE_CUSTOM("自定义表盘", "该例实现替换表盘背景，并下载到设备上"),

    //    DICT("词典下载", "下载单词本到设备")
    VP9012_BATCH("VP9012批量升级", "选择后缀为Zip升级包"),
    VP9012_CHECK("VP9012批量检测", "选择后缀为Zip升级包"),

    POWER_CONFIG("功率曲线", "设置功率曲线")
}

@Composable
private fun UrlItem(context: Context, title: String, url: String, enable: Boolean = true) {
    Column(
        modifier = Modifier
            .clickable {
                if (enable) {
                    val uri = Uri.parse(url)
                    context.startActivity(Intent(Intent.ACTION_VIEW, uri))
                }
            }
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleSmall,
            color = MaterialTheme.colorScheme.secondary
        )
        Text(
            text = url,
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )
    }
}

@Composable
private fun MenuItem(title: String, desc: String, onTap: () -> Unit) {
    Column(
        modifier = Modifier
            .clickable { onTap.invoke() }
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )
        Text(
            text = desc,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
            modifier = Modifier.fillMaxWidth(),
            textAlign = TextAlign.Center
        )
    }
}